package com.hll.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "PageEncodingFilter")
public class PageEncodingFilter implements Filter {
    private String encoding = "UTF-8";
    protected FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;
        if (filterConfig.getInitParameter("encoding") != null) {//获取xml参数encoding的值，若不为空，则下面设置的为本类中的encoding，即UTF-8;
            encoding = filterConfig.getInitParameter("encoding");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        request.setCharacterEncoding(encoding);
        //测试
        String uri = request.getRequestURI();
        String requestedUrl = uri.substring(request.getContextPath().length() + 1 );//去掉ContextPath
        System.out.println(uri + " = " + requestedUrl);

        filterChain.doFilter(request, servletResponse);//请求继续往下走
    }

    @Override
    public void destroy() {
        this.encoding = null;
    }

}
